package org.mark.sell.service.impl;

import org.mark.common.response.Result;
import org.mark.sell.entity.DeliveryProcess;
import org.mark.sell.mapper.DeliveryProcessMapper;
import org.mark.sell.service.DeliveryProcessService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeliveryProcessServiceImpl extends ServiceImpl<DeliveryProcessMapper, DeliveryProcess> implements DeliveryProcessService {

    @Override
    public Result getSalesStatistics(Map<String, Object> params) {
        try {
            // 如果没有传入时间参数，设置默认时间范围为最近一年
            String startTime = params.get("startTime") != null ? 
                params.get("startTime") + " 00:00:00" : 
                "2024-01-01 00:00:00";
            
            String endTime = params.get("endTime") != null ? 
                params.get("endTime") + " 23:59:59" : 
                "2024-12-31 23:59:59";
            
            String userName = (String) params.get("userName");
            String freshFoodName = (String) params.get("freshFoodName");

            // 获取配送员统计
            List<Map<String, Object>> deliveryStats = baseMapper.getDeliveryStats(startTime, endTime, userName, freshFoodName);
            if (deliveryStats == null) {
                deliveryStats = new ArrayList<>();
            }

            // 获取生鲜统计
            List<Map<String, Object>> freshStats = baseMapper.getFreshStats(startTime, endTime, userName, freshFoodName);
            if (freshStats == null) {
                freshStats = new ArrayList<>();
            }

            // 计算总计数据
            double totalAmount = 0;
            int totalNumber = 0;
            double promotionAmount = 0;

            for (Map<String, Object> stat : deliveryStats) {
                if (stat.get("total_amount") != null) {
                    totalAmount += ((Number) stat.get("total_amount")).doubleValue();
                }
                if (stat.get("total_number") != null) {
                    totalNumber += ((Number) stat.get("total_number")).intValue();
                }
                if (stat.get("promotion_amount") != null) {
                    promotionAmount += ((Number) stat.get("promotion_amount")).doubleValue();
                }
            }

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("totalAmount", totalAmount);
            result.put("totalNumber", totalNumber);
            result.put("promotionAmount", promotionAmount);
            result.put("deliveryStats", deliveryStats);
            result.put("freshStats", freshStats);

            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("获取统计数据失败：" + e.getMessage());
        }
    }
}